/*
 * SerialPort.cpp
 *
 *  Created on: May 12, 2011
 *      Author: stud
 */

#include "SerialPort.h"

SerialPort::SerialPort(char * device,int baudRate)
{
	this->baudRate = baudRate;
	this->device = device;
	this->fd = -1;
}

SerialPort::~SerialPort()
{

}

int SerialPort::serialPortInit()
{

		this->fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY);
		if (this->fd >0) // In the case the port has been opened
		{
			fcntl(fd, F_SETFL, 0); // Set file status flag

			// Set port configuration
			struct termios options;


			// Get current port configuration
			tcgetattr(fd, &options);

			// Configure Input and Output baudrates
			cfsetispeed(&options, baudRate);
			cfsetospeed(&options, baudRate);

			// 8N1
			options.c_cflag &= ~PARENB;
			options.c_cflag &= ~CSTOPB;
			options.c_cflag &= ~CSIZE;
			options.c_cflag |= CS8;

			options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // Choosing RAW mode

			options.c_cflag |= (CLOCAL | CREAD);

			options.c_cc[VTIME] = 10; // Timer of 1 sec (VTIME * 0.1 = timeout in seconds)
			options.c_cc[VMIN] = 0; // Minimum number of characters before satisfying a read call

			tcflush(fd, TCIFLUSH); // Flush the port

			tcsetattr(fd, TCSANOW, &options);
		}

	return this->fd;
}


int SerialPort::readBlock(unsigned char * buff, int len)
{
	int count = 0;
	unsigned char readByte = 0;
	int readResult = 0;

	while (count < len) {
		readResult = read(fd, &readByte, 1);
		if (readResult != 1) {
			return -1; // Problem in the reading
		} else // One byte read correctly
		{
			buff[count] = readByte;
			count++;
		}
	}

	return count;
}

int SerialPort::writeBlock(unsigned char * buff,int len)
{
	return write(fd, buff, len);
}

int SerialPort::getBaudRate()
{
	return this->baudRate;
}
char * SerialPort::getDeviceName()
{
	return this->device;
}
int SerialPort::getFd()
{
	return this->fd;
}

int SerialPort::close()
{

}
